<template>
  <div>
    <Frame
      class="frame"
      flexType="flex"
      size="small-2"
      title="线盘控制密码"
      content2="content2"
      :visible="dialogVisible"
    >
      <template #default>
        <el-form
          :model="addForm"
          :rules="rules"
          ref="refForm"
          label-width="100px"
          inline
        >
          <span v-if="current != 'password'">
            <el-form-item size="small" label="手机号码" prop="mobile">
              <el-input
                style="width: 300px"
                clearable
                disabled
                v-model="addForm.mobile"
                placeholder="请输入"
                maxlength="11"
              ></el-input>
            </el-form-item>
            <el-form-item size="small" label="短信验证码" prop="smsCode">
              <el-input
                style="width: 300px"
                clearable
                v-model="addForm.smsCode"
                placeholder="请输入"
                maxlength="6"
              >
                <el-button slot="append" @click="smsCodeClick">
                  <span v-show="showCountDown">获取验证码</span>
                  <span v-show="!showCountDown">{{ countDown }}秒重新获取</span>
                </el-button></el-input
              >
            </el-form-item>
          </span>
          <el-form-item size="small" label="指令密码" prop="password">
            <el-input
              v-model="addForm.password"
              show-password
              clearable
              placeholder="请输入指令密码"
              size="small"
              style="width: 300px"
              maxlength="20"
              oninput="value=value.replace(/\s*/g,'')"
              readOnly
              autocomplete="off"
              @focus="onFocus"
              @blur="onBlur"
              @input.native="onInput($event, addForm.password)"
              @mousedown.native="onMousedown"
            >
            </el-input>
          </el-form-item>
        </el-form>

        <div class="tip" v-if="!statusInfo.cmdPasswordState">
          <span class="label">温馨提示：</span>
          您尚未设置指令密码。为确保安全，请先通过短信验证身份，再设置密码。完成后，即可使用指令远程管理设备。
        </div>
      </template>
      <template #footer>
        <div class="footer-btns">
          <el-button size="small" @click="cancel">取消</el-button>
          <el-button size="small" @click="submit" v-preventReClick="1000"
            >确认</el-button
          >
        </div>
      </template>
    </Frame>
  </div>
</template>

<script>
import {
  getSmsCode,
  reqUtdQueryPassword,
  reqUtdSetPassword,
  reqKeyCommandSend,
} from "@api/api.js";
import {
  validateNumberLetter,
  validateNumber,
  validateNoChinese,
} from "@utils/validate";
import { mapState } from "vuex";
import Frame from "./frame.vue";

export default {
  props: ["statusInfo", "commandInfo"],
  components: { Frame },
  data() {
    return {
      dialogVisible: false,

      current: "",
      title: "短信验证",

      addForm: {
        mobile: "",
        smsCode: "",
        password: "",
      },
      rules: {
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
        ],
        smsCode: [
          { required: true, message: "请输入短信验证码", trigger: "blur" },
          { validator: validateNumber },
        ],
        password: [
          { required: true, message: "请输入指令密码", trigger: "blur" },
          {
            min: 6,
            max: 20,
            message: "密码长度为6-20位",
            trigger: "blur",
          },
          { validator: validateNoChinese },
        ],
      },

      showCountDown: true, //显示倒计时
      countDown: "", //倒计时一分钟
      intervalId: null, //定时器
    };
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        if (this.statusInfo.cmdPasswordState) {
          this.current = "password";
        } else {
          this.current = "edit";
        }
      }
    },
  },
  computed: {
    ...mapState(["user"]),
  },
  mounted() {
    this.addForm.mobile = this.user.mobile;
  },
  methods: {
    // 点击获取短信验证码
    async smsCodeClick() {
      if (!this.addForm.mobile)
        return this.$modal.notifyWarning("请输入手机号");
      if (this.addForm.mobile.length < 11)
        return this.$modal.notifyWarning("手机号码为11位数字");
      if (!this.showCountDown) return; //60s内只需发一次验证码

      // 发送验证码
      let res = await getSmsCode({
        mobile: this.addForm.mobile,
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifyWarning("请注意查收手机短信验证码");
      this.showCountDown = false;
      this.countDown = 60;
      this.intervalId && clearInterval(this.intervalId);
      this.intervalId = setInterval(() => {
        if (this.countDown > 0 && this.countDown <= 60) {
          this.countDown--;
        } else {
          this.showCountDown = true;
          clearInterval(this.intervalId);
          this.intervalId = null;
        }
      }, 1000);
    },

    // 取消
    cancel() {
      this.$emit("update", "cancel");
      this.closeDialog();
    },
    // 点击绑定
    submit() {
      this.$refs.refForm.validate(async (valid) => {
        if (!valid) return;
        // 设备详情进来
        if (this.statusInfo.cmdPasswordState) {
          // 已设置有密码
          this.keyCommandSendFoo();
        } else {
          // 未设置密码，需设置密码
          this.utdSetPasswordFoo();
        }
      });
    },

    async utdSetPasswordFoo() {
      let res = await reqUtdSetPassword({
        // deviceCode: this.deviceInfo.imei,
        deviceCode: this.commandInfo.deviceCode || this.commandInfo.imei,
        password: this.addForm.password,
        mobile: this.addForm.mobile,
        code: this.addForm.smsCode,
      });
      if (res.code !== 20000) {
        this.$modal.notifyWarning(res.message);
        return;
      }
      this.$emit("update", "submit");
      this.$modal.notifySuccess("设置成功");
      this.closeDialog();
    },

    async keyCommandSendFoo(isCloseDialog = false) {
      // let id;
      // if (!this.commandInfo.startId && !this.commandInfo.stopId) {
      //   id = this.commandInfo.id;
      // } else if (
      //   (this.commandInfo.startId || this.commandInfo.stopId) &&
      //   this.commandInfo.switch
      // ) {
      //   id = this.commandInfo.startId;
      // } else if (
      //   (this.commandInfo.startId || this.commandInfo.stopId) &&
      //   !this.commandInfo.switch
      // ) {
      //   id = this.commandInfo.stopId;
      // }
      let res = await reqKeyCommandSend({
        // deviceCode: this.deviceInfo.imei || this.deviceInfo.deviceCode,
        deviceCode: this.commandInfo.deviceCode || this.commandInfo.imei,
        id: this.commandInfo.switch
          ? this.commandInfo.startId
          : this.commandInfo.stopId,
        password: this.addForm.password,
      });
      if (res.code !== 20000) {
        if (isCloseDialog) {
          this.closeDialog();
        }
        this.$modal.notifyWarning(res.message);
        return;
      }
      this.$emit("update", "submit");
      this.$modal.notifySuccess("指令下发成功");
      this.closeDialog();
    },

    // 点击关闭弹框
    closeDialog() {
      this.$refs.refForm.resetFields();
      this.showCountDown = true;
      this.countDown = 60;
      this.intervalId && clearInterval(this.intervalId);
      this.current = "";
      this.addForm.smsCode = this.addForm.password = "";
      this.$parent.showShade = false;
      this.dialogVisible = false;
    },

    // 获取焦点
    onFocus(event) {
      setTimeout(function () {
        event.target.readOnly = false;
      }, 100);
    },
    // 失去焦点
    onBlur(event) {
      event.target.readOnly = true;
    },
    // 防止内容删完时出现账号和密码
    onInput(event, val) {
      if (val.length === 0) {
        this.onBlur(event);
        this.onFocus(event);
      }
    },
    // 防止多次点击时出现账号和密码
    onMousedown(event) {
      this.onBlur(event);
      this.onFocus(event);
    },
  },
};
</script>

<style lang="less" scoped>
@import url("../../../../views/common.less");

// input后面的查询按钮
::v-deep .el-input-group__append {
  color: #fff;
  border: none;
  background-color: #7367f0;
}

.tip {
  color: #999;
  font-size: 12px;
  line-height: 22px;
  padding-left: 30px;

  .label {
  }
}

.footer-btns {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
</style>
